package com.sdry.web.controller.jyy.plan;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sdry.model.jyy.plan.NeedOrder;
import com.sdry.model.jyy.plan.Needs;
import com.sdry.model.jyy.plan.Plan2t;
import com.sdry.model.jyy.plan.PlanDetail;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.plan.Product;
import com.sdry.model.plan.StorageArea;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.jyy.plan.NeedOrderService;
import com.sdry.service.jyy.plan.NeedsService;
import com.sdry.service.jyy.plan.Plan2tService;
import com.sdry.service.jyy.plan.PlanDetailService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.service.lz.WarehouseService;
import com.sdry.service.plan.ProductService;
import com.sdry.service.plan.StorageAreaService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;
/**
 *
 *@ClassName: Plan2tController
 *@Description: 生产计划
 *@Author llm
 *@Date 2019-07-02 17:32:04
 *@version 1.0
 *
 * 修改人：连雷明
 * 修改时间：2019-11-08
 * 修改内容：88-91行，添加参数，仓库ID
*/
@Controller
@RequestMapping("/plan2tManager")
public class Plan2TController{
	@Resource Plan2tService plan2tService;
	@Resource PlanDetailService PlanDetailService;
	@Resource ProductService productService;
	@Resource WarehouseService warehouseService;
	@Resource StockOutOrderService stockOutOrderService;
	@Resource StorageAreaService storageAreaService;
	@Resource MaterielService materielService;
	@Resource NeedOrderService needOrderService;
	@Resource NeedsService needsService;
	/** 
	 * 进入页面
	 * @param model
	 * @return 页面路径
	*/
	@RequestMapping("/page")
	public ModelAndView pagePlan2t (Model model, HttpSession session) {
		
		Long warehouseId = (Long)session.getAttribute("warehouse_id");
		
		ModelAndView mav = new ModelAndView();
		//-----------------------------jyy2019-11-08start---------------------------------
		List<Warehouse> allWarehouse = warehouseService.queryAllWarehouse(warehouseId);
		//-----------------------------jyy2019-11-08end-----------------------------------
		mav.addObject("allWarehouse", allWarehouse);
		List<Customer> allSupplier = stockOutOrderService.queryAllCustomerByType();
		mav.addObject("allSupplier", allSupplier);
		/********************* llm 19.11.08 修改 start  ******************/
		List<Customer> allClient = stockOutOrderService.queryAllCustomerByType1(warehouseId);
		/********************* llm 19.11.08 修改 end  ******************/
//		List<Customer> allClient = stockOutOrderService.queryAllCustomerByType1();
		mav.addObject("allClient", allClient);
		mav.setViewName("/jyy/plan/2tPlan");
		return mav;
	}
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public Plan2t queryById(Long id) {
		Plan2t param = plan2tService.queryById(id);
		return param;
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<Plan2t> queryAllByMution(Plan2t param) {
		List<Plan2t> list = plan2tService.queryAllByMution(param);
		return list;
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/list")
	public void list(Plan2t param, HttpServletResponse response){
		/*
		 * 条件分页查询内容
		 */
		List<Plan2t> list = plan2tService.findPageByMution(param);
		/*
		 * 条件查询总条数
		 */
		Integer total = plan2tService.selectCountByMution(param);
		/*
		 * 转为json数据传至页面
		 */
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/insert")
	public void insert(Plan2t param, HttpServletResponse response){
		Long id = plan2tService.insert(param);
		try {
			response.getWriter().print(id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/update")
	public void update(Plan2t param,HttpServletResponse response){
		Integer count = plan2tService.update(param);
		try {
			response.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletResponse response){
		ids=ids.replace("'",""); 
		Integer count = plan2tService.delete(ids);
		try {
			response.getWriter().print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 上传生产计划
	 * @param file	上传的文件
	 * @param response
	 */
	@RequestMapping(value="/uploadPlan2t", method = RequestMethod.POST)
    @ResponseBody
	public Map<String, Object> uploadPlan2t(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>();
	    String desFilePath = "";
		// 1.获取原文件名1
        String newName = file.getOriginalFilename();
		// 2.获取要保存的路径文件夹1
		String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
		// 3.保存
		desFilePath = realPath + "\\" + newName;
		File desFile = new File(desFilePath);
		try {
			file.transferTo(desFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		map.put("fileName",newName);
		map.put("isSuccess",1);
		return  map;
	}
	
	/**
     * 把生产计划存入数据库
     * @param param
     * @param response
     * @return
     */
    @RequestMapping("/importPlan2t")
    public void importPlan2t(Plan2t param, HttpServletRequest request, HttpServletResponse response){
        String fileName = param.getFileName();
        String savePath = request.getSession().getServletContext().getRealPath("/uploadFile/"+fileName);
        //取文件后缀
        String subfix = fileName.lastIndexOf(".")==-1? "" : fileName.substring(fileName.lastIndexOf(".")+1);
        List<List<String>> lists = new ArrayList<>();
        //获取导入列数
        int num = 14;
        try {
            //用工具类读取导入的文件
            if(subfix.equals("xls")){
                lists = ExcelUtils.readXls(savePath, request, num);
            }else if(subfix.equals("xlsx")){
                    lists = ExcelUtils.readXlsx(savePath, request, num);
            }else{
                    response.getWriter().print("0");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        int flag = 1;
        Plan2t plan = new Plan2t();
		PlanDetail planDetail = new PlanDetail();
		Product product = new Product();
        Long affact = 0L;
        Long detailId = 0L;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  
        plan.setSupplier_id(param.getSupplier_id());
        plan.setClient_id(param.getClient_id());
        plan.setWarehouse_id(param.getWarehouse_id());
        plan.setStatus1(0+"");
        plan.setStatus2(0+"");
        //计划单号
        plan.setPlan_number("P"+DateUtil.dateFormat4());
        //计划时间
        plan.setStart_date(sdf.format(new Date()));
        ZcSysUserEntity user = (ZcSysUserEntity)request.getSession().getAttribute("user");
        plan.setUser_id(user.getId());
        plan.setCreate_date(sdf.format(new Date()));
        //保存生产计划
        affact = plan2tService.insert(plan);
        if(affact > 0) {
            	  //获取每一行要导入的数据，第一列车型
            for (int i = 0; i < lists.size(); i++) {
                List<String> list = new ArrayList<>();
                list= lists.get(i);
                
                //获取返回排产单id
                planDetail.setPlanid(affact);
                /**
                 * 重复开始的地方
                 * 一个计划单有多个产品
                 * 1、2、3列存入详情
                 */
				//根据产品名称，编号，查询ID，存入计划详情
				//product.setProductName(list.get(2));	
                //车型
				product.setProductNumber(list.get(0));
				//总计划量
				planDetail.setTsum(list.get(1));  
				planDetail.setT67(list.get(2));
				planDetail.setT89(list.get(3));
				planDetail.setT1011(list.get(4));
				planDetail.setT1213(list.get(5));
				planDetail.setT1415(list.get(6));
				planDetail.setT1617(list.get(7));
				planDetail.setT1819(list.get(8));
				planDetail.setT2021(list.get(9));
				planDetail.setT2223(list.get(10));
				planDetail.setT01(list.get(11));
				planDetail.setT23(list.get(12));
				planDetail.setT45(list.get(13));
				
				Long productId = productService.queryIdByMution(product);
				if(productId != null && productId > 0){
					planDetail.setPid(productId);
	                //添加生产计划详情
	                detailId = PlanDetailService.insert(planDetail);
	                /**
	                 * 结束重复的地方
	                 */
	                if(detailId <= 0){
	                	//如果详情添加失败，删除已添加的生产计划
	                	plan2tService.delete(affact.toString());
	                    flag = 0;
	                    break;
	                }
				}else{
					//如果详情添加失败，删除已添加的生产计划
					plan2tService.delete(affact.toString());
                    flag = -1;
                    break;
				}
            }
        }
        try {
            response.getWriter().print(flag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 根据生产计划生成发货单  
     * @param id	主键ID
     * @param response	
     *1、根据计划单ID查所有产品（集合）
     *2、根据产品找到对应的bom（遍历产品集合，生成物料集合）
     *3、遍历物料集合
     *3.1、用计划数量-库存数量=发货数量，存入物料集合
     *3.2、查供应商ID存入新的供应商集合，存入物料集合（供应商ID存入两个集合）
     *4、把供应商集合转为set集合，以去重，又把set转为新的供应商集合
     *5、遍历供应商集合，在内部遍历物料集合，如果供应商ID与物料集合的供应商ID一样，供应商ID存入发货单，物料ID，数量存入发货单详情
     */
    @RequestMapping("/createShipmentsTask")
    public void createShipmentsTask(Long id, HttpServletRequest request, HttpServletResponse response){
    	
    	int flag = 0;
    	
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	ZcSysUserEntity user = (ZcSysUserEntity)request.getSession().getAttribute("user");
    	//根据id查询2T生产计划单
    	Plan2t plan = plan2tService.queryById(id);
    	
    	//第一步、获取计划单所有产品，存入集合：productList
    	PlanDetail pd = new PlanDetail();
		pd.setPlanid(id);
		List<PlanDetail> list1 = PlanDetailService.queryAllByMution(pd);
		
		//第二步、根据 bom，获取所有物料，存入集合：bomNeeds
    	StringBuffer ids = new StringBuffer();
		for (int i = 0; i < list1.size(); i++ ) {
			if(i == 0) {
				ids.append("("+list1.get(i).getPid());
			}else {
				ids.append(","+list1.get(i).getPid());
			}
		}
		ids.append(")");
		System.out.println(ids.toString());
		pd.setPids(ids.toString());
		List<Needs> bomNeeds  = plan2tService.selectBomBypid(pd);
    	
        //第四步、遍历物料集合，查询线边库存，计算发货数量
        Set<Long> supplierSet = new HashSet<>();
        StorageArea sa = new StorageArea();
        for (Needs need : bomNeeds) {
        	sa.setMaterielId(need.getMid());
        	sa.setPage(1);
        	sa.setLimit(10);
			List<StorageArea> li = storageAreaService.findPageByMution(sa);
        	if(li.size() > 0){
        		//线边库数量
        		need.setXstock(li.get(0).getMaterielQuantity());
        		
        		if(li.get(0).getLowers() != null) {
        			//线边安全库存
            		need.setAstock(li.get(0).getLowers());
        		}else {
        			//线边安全库存
            		need.setAstock(0);
        		}
        		
        	}else{
        		//线边库数量
        		need.setXstock(0);
        		//线边安全库存
        		need.setAstock(0);
        	}
        	
        	//恒安库存
        	//总需求量
        	//6-7小时库存
        	need.setStock67(need.getXstock() - need.getT67());
        	//小时需求量
        	need.setNeed67(need.getT67() + need.getT89() + need.getAstock() - need.getXstock());
        	//8-9小时库存
        	need.setStock89(need.getStock67() - need.getT89());
        	//8-9小时需求量
        	need.setNeed89(need.getT89() + need.getT1011() + need.getAstock() - need.getStock67());
        	//8-9小时到货后库存
        	need.setAfter89(need.getStock89() + need.getNeed89() - need.getT89());
        	//10-11小时库存
        	need.setStock1011(need.getAfter89() - need.getT1011());
        	//10-11小时需求量
        	need.setNeed1011(need.getT1011() + need.getT213() + need.getAstock() - need.getAfter89());
        	//10-11小时到货后库存
        	need.setAfter1011(need.getAfter89() - need.getT1011());
        	//12-13小时库存
        	need.setStock1213(need.getAfter1011() - need.getT213());
        	//12-13小时需求量
        	need.setNeed1213(need.getT213() + need.getT1415() + need.getAstock() - need.getAfter1011());
        	//12-13小时到货后库存
        	need.setAfter1213(need.getAfter1011() - need.getT213());
        	//14-15小时需求量
        	need.setNeed1415(need.getT1415() + need.getT1617() + need.getAstock() - need.getAfter1213());
        	//16-17小时需求量
        	//need.setNeed1617(need.getT1617() + need.getT1819() + need.getAstock() - );
        	
        	//TODO
        	
        	//根据物料ID查供应商
        	Materiel materiel = materielService.queryMaterielById(need.getMid());
        	need.setSupplierId(materiel.getCustomer_id());
        	supplierSet.add(materiel.getCustomer_id());
		}
        
      //第五步、根据不同的供应商生成多个发货单
        NeedOrder needOrder = new NeedOrder();
        start:for(Long supplierId : supplierSet){
        	needOrder.setUser_id(user.getId());
        	needOrder.setCreate_date(sdf.format(new Date()));
        	needOrder.setWarehouse_id(plan.getWarehouse_id());
        	needOrder.setSupplier_id(supplierId);
        	needOrder.setPlan_id(id);
        	needOrder.setStatus(0+"");
        	//保存计划单
        	Long affct = needOrderService.insert(needOrder);
        	if(affct > 0){
        		for(Needs need : bomNeeds){
            		if(supplierId == need.getSupplierId()){
            			need.setOrderId(affct);
            			//保存计划单详情
            			Long nid = needsService.insert(need);
            			if(nid > 0){
            				flag = 1;
            			}else {
            				break start;
            			}
            		}
            	}
        	}else{
        		flag = 0;
				break;
        	}
        }
        
       //修改生产单状态
        if(flag > 0) {
        	 plan.setStatus1(1+"");
        	 plan2tService.update(plan);
        }
       
        try {
			ResponseUtil.write(response, flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
   
}
